package ua.kharkov.khpi.tarasenko.bach.analysis.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ua.kharkov.khpi.tarasenko.bach.analysis.prefixspan.Item;
import ua.kharkov.khpi.tarasenko.bach.analysis.prefixspan.PseudoDbPS;
import ua.kharkov.khpi.tarasenko.bach.analysis.prefixspan.Sequence;
import ua.kharkov.khpi.tarasenko.bach.core.logging.TransactionType;

public final class FileUtils {

	public static PseudoDbPS getDBFromFile(File input) throws IOException {
		PseudoDbPS db = new PseudoDbPS();
		BufferedReader reader = new BufferedReader(new FileReader(input));
		Pattern row = Pattern.compile("(\\d+)\\|(.+)\\|(\\d+)");
		String inputRow = "";
		Matcher m = null;
		String lastTransId = "";
		String currentTransId = "";
		Sequence curSeq = new Sequence();
		while ((inputRow = reader.readLine()) != null) {
			m = row.matcher(inputRow);
			if (m.find()) {
				String transId = m.group(1);
				String itemId = m.group(2);
				String actionId = m.group(3);

				currentTransId = transId;
				if (!currentTransId.equals(lastTransId)) {
					db.addRow(curSeq);
					curSeq = new Sequence();
				}
				if (Integer.valueOf(itemId) > 2500) {
					continue;
				}
				Item item = Item.getItem(itemId);
				item.setTransactionType(TransactionType.getTransType(Integer
						.parseInt(actionId)));
				curSeq.addItem(item);

				lastTransId = currentTransId;
			}
		}
		
		reader.close();
		if (!curSeq.isEmpty()) {
			db.addRow(curSeq);
		}
		return db;
	}
}
